package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl  extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private EmpService empService;
    @Override
    public PageResult<Clazz> pageClazz(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //分页查询,创建page对象
        Page<Clazz> pageInfo = new Page<>(page, pageSize);
        //按照时间倒序排序
        pageInfo.addOrder(OrderItem.desc("update_time"));
        //按照条件进行查询
        lambdaQuery().like(name != null, Clazz::getName, name).between(begin != null && end != null, Clazz::getBeginDate, begin, end).page(pageInfo);
        //获取结果emp表的名字为班主任名字
        //获取总记录数的集合
        List<Clazz> list = pageInfo.getRecords();
        //获取班级中的所有masterid
        List<Integer> listClazz = list.stream().map(Clazz::getMasterId).collect(Collectors.toList());
        //根据masterid查询所有班主任
        if(!CollectionUtils.isEmpty(listClazz)){
            List<Emp> clazzList = empService.listByIds(listClazz);
            if(!CollectionUtils.isEmpty(clazzList)){
            //
            clazzList.forEach(clazz -> {
                list.forEach(emp -> {
                    if(emp.getId().equals(clazz.getId()) && emp.getId()!=null){
                        emp.setMasterName(clazz.getName());
                    }

                });
            });}
        }
        //封装结果
        PageResult<Clazz> pageResult = new PageResult<>(pageInfo.getTotal(), list);

        return pageResult;
    }
}
